﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ANZ_AIM_BLL;
using ANZ_AIM_FRAMEWORK;
using ANZ_AIM_BLL.Model;
using ANZ_AIM_GUI.Utils;
using System.Text.RegularExpressions;
using System.Diagnostics;

namespace ANZ_AIM_GUI
{
    public partial class frmSalePIPUpload : Form
    {
        public List<SalePIP> salePIPList = new List<SalePIP>();
        public frmSalePIPUpload()
        {
            InitializeComponent();
        }

        private void btnOpenFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog ExcelDialog = new OpenFileDialog();
            ExcelDialog.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";
            ExcelDialog.InitialDirectory = @"E:\Database\Excel";
            ExcelDialog.Title = "Select your file excel";
            if (ExcelDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtFileName.Text = ExcelDialog.FileName;
                txtFileName.ReadOnly = true;
            }
        }

        private void btnUpload_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txtFileName.Text.Trim()))
                {
                    MessageBox.Show("File Name cannot be empty.", Constant.SYS_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtFileName.Focus();
                    return;
                }

              

                //insert BatchFileSaleInfo DB
                int IDFileBatchUpload = 0;
                BatchFileSaleInfoUploadBLL batchFileSaleInfoBll = new BatchFileSaleInfoUploadBLL();
                string[] s = txtFileName.Text.Trim().Split('\\');
                batchFileSaleInfoBll.Save(new BatchFileSaleInfoUpload() { CreatedDate = MiscHelper.DateTimeToShort(DateTime.Now), FileName = s[s.Length - 1], Status = Constant.NEED_TO_VERIFY, Type = Constant.TYPE_PIP }, ref IDFileBatchUpload);

                frmSplash.ShowSplashScreen();

                var watch = Stopwatch.StartNew();
                ////bind datarow to list 
                DataTable dtData = NPOIHelper.ImportExceltoDt(txtFileName.Text.Trim(), 0, 0);

                watch.Stop();
                var sasd = watch.Elapsed;

                foreach (DataRow dr in dtData.Rows)
                {
                    PackObject(dr, IDFileBatchUpload.ToString());
                }

                var elapsedMs1 = watch.Elapsed;
              
                ////insert SQMTemp
                SalePIPBLL salePIPBll = new SalePIPBLL();
                salePIPBll.SavePIP(salePIPList);

                frmSplash.CloseForm();

               
                var elapsedMs = watch.Elapsed;
                watch.Stop();

                //bind datagridview
                DataTable dt = new DataTable();
                dt.Columns.Add("Batch File Change");
                dt.Columns.Add("File Name");
                dt.Columns.Add("Uploaded Date");

                DataRow datarow = dt.NewRow();
                datarow["Batch File Change"] = IDFileBatchUpload;
                datarow["File Name"] = s[s.Length - 1];
                datarow["Uploaded Date"] = DateTime.Now;
                dt.Rows.Add(datarow);

                dgvData.DataSource = null;
                dgvData.Columns.Clear();
                dgvData.DataSource = dt;
                dgvData.AutoResizeColumns();

                MessageBox.Show("Upload Successfully.", Constant.SYS_INFORMATION, MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
            catch (Exception ex)
            {

            }
        }

        private void PackObject(DataRow drData, string batchFileSaleInfoID)
        {
            SalePIP salePIP = new SalePIP();
            salePIP.SaleCode = drData["Sales Code"].ToString();
            salePIP.Role = drData["Role"].ToString();
            salePIP.EmployeeFullName = drData["Employee Full Name"].ToString();
            salePIP.Level = drData["Level"].ToString();
            salePIP.PIPTarget = drData["PIPTarget"].ToString();
            salePIP.PIPM1Result = drData["PIPM1Result"].ToString();
            salePIP.PIPM2Result = drData["PIPM2Result"].ToString();
            salePIP.CurrentMonthPIPStatus = drData["Current Month PIP Status"].ToString();
            salePIP.Month = drData["Month"].ToString();
            salePIP.BatchFileSaleInfoID = batchFileSaleInfoID;
            salePIP.Status = Constant.NEED_TO_VERIFY;

            salePIPList.Add(salePIP);
        }

        public DataTable ConvertToDataTable<T>(List<T> data)
        {
            PropertyDescriptorCollection properties =
               TypeDescriptor.GetProperties(typeof(T));
            DataTable table = new DataTable();
            foreach (PropertyDescriptor prop in properties)
                table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
            foreach (T item in data)
            {
                DataRow row = table.NewRow();
                foreach (PropertyDescriptor prop in properties)
                    row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                table.Rows.Add(row);
            }
            return table;

        }

        private void dgvData_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                int selectedRowCount = dgvData.Rows.GetRowCount(DataGridViewElementStates.Selected);
                if (selectedRowCount > 0)
                {
                    DataRow dr = ((DataRowView)dgvData.SelectedRows[0].DataBoundItem).Row;
                    frmDataSaleInfoUpload frmDateSaleInfoUpload = new frmDataSaleInfoUpload(dr[0].ToString());
                    frmDateSaleInfoUpload.ShowDialog(this);
                }
            }
            catch (Exception ex)
            {

            }
        }
    }
}
